package site.oldpei.manage.nomal.utils;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.stream.Collectors;


public class GetYoukuList {
    private static final String downloadPath = "E:\\抗韩中年人\\";
    private static final String checkPath = "E:\\抗韩中年人\\抗韩中年人\\";

    private static List<File> fileList;

    public static void main(String[] args) throws IOException, InterruptedException {
        File file = new File("C:\\Users\\peijixing\\Desktop\\【抗韩中年人】 - 播单 - 优酷视频.html");
        byte[] bytes = FileUtil.readBytes(file);
        String html = new String(bytes);
        Document document = Jsoup.parse(html);
        for (int i = 1; i < 20; i++) {
            initFileList();
            String cssSelector = "#playList > div:nth-child(" + i + ") > div > a";
            Elements select = document.select(cssSelector);
            if (select.isEmpty()) {
                break;
            } else {
                String title = select.attr("title");
                if (!checkTitle(title)) {
                    continue;
                }
                String href = select.attr("href");
                href = href.substring(0, href.indexOf("?"));
                String cmdCommand = "yt-dlp " + href + " -o " + downloadPath + "%(title)s.%(ext)s";
                cmd(cmdCommand);
            }
        }


    }

    private static boolean checkTitle(String title) {
        if (title.contains("冠军")) {
            return false;
        }
        List<File> collect = fileList.stream().filter(file -> file.getName().contains(title)).collect(Collectors.toList());
        if (!collect.isEmpty()) {
            System.out.println(title + "已经下载了");
        }
        return collect.isEmpty();
    }

    private static void initFileList() {
        if (fileList == null) {
            fileList = CollectionUtil.newArrayList(FileUtil.ls(downloadPath));
            fileList.addAll(CollectionUtil.newArrayList(FileUtil.ls(checkPath)));
        }
    }

    private static String cmd(String cmdCommand) throws IOException {
        /* 记得引入java.io中的相关包 */
        // 获取进程
        Process process = Runtime.getRuntime().exec("cmd /c " + cmdCommand); // 运行dir命令
        // 获取进程的输入流 流的方向为(唤醒的进程 -> java程序)
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line;
        // 若读取当前行不为空，就将其输出
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
        // 将流关闭，避免浪费系统资源
        reader.close();
        return line;
    }
}
